package com.buddies.lottery.ui.user;

import android.content.DialogInterface;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseFragment;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.common.Constants;
import com.buddies.lottery.data.resp.CheckWalletPwdResponse;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.ui.agent.register.AgentRegisterActivity;
import com.buddies.lottery.ui.customer.CustomerActivity;
import com.buddies.lottery.ui.login.LoginActivity;
import com.buddies.lottery.ui.lottery.bet.LotteryBetRecordActivity;
import com.buddies.lottery.ui.pay.PayActivity;
import com.buddies.lottery.ui.user.pwd.ResetPasswordActivity;
import com.buddies.lottery.ui.wallet.bank.BankActivity;
import com.buddies.lottery.ui.wallet.pwd.UpdateWalletPwdActivity;
import com.buddies.lottery.ui.web.WebActivity;
import com.buddies.lottery.ui.withdraw.WithdrawActivity;
import com.buddies.lottery.utils.LotteryUtils;
import com.buddies.lottery.widget.ObservableScrollView;
import com.buddies.lottery.widget.OnTabClickListener;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;

public class UserFragment extends BaseFragment<UserContract.Presenter> implements OnTabClickListener, View.OnClickListener, UserContract.View {

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ObservableScrollView mScrollView;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    public void initView() {
        mSwipeRefreshLayout = ((SwipeRefreshLayout) findViewById(R.id.refresher));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        mScrollView = (ObservableScrollView) findViewById(R.id.scrollView);
        mScrollView.setOnScrollChangedListener(new ObservableScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int x, int y, int oldx, int oldy) {
                mSwipeRefreshLayout.setEnabled(mScrollView.getScrollY() == 0);
            }
        });

        findViewById(R.id.tv_reset_passward).setOnClickListener(this);

        findViewById(R.id.item_wallet).setOnClickListener(this);
        findViewById(R.id.tv_charge).setOnClickListener(this);
        findViewById(R.id.tv_withdraw).setOnClickListener(this);

        findViewById(R.id.item_bank).setOnClickListener(this);
        findViewById(R.id.item_wallet_pwd).setOnClickListener(this);
        findViewById(R.id.item_notification).setOnClickListener(this);
        findViewById(R.id.item_lottery).setOnClickListener(this);
        findViewById(R.id.item_agent).setOnClickListener(this);
        findViewById(R.id.item_version).setOnClickListener(this);
        findViewById(R.id.item_log_report).setOnClickListener(this);
        findViewById(R.id.item_logout).setOnClickListener(this);
    }

    @Override
    public void initData() {
        mPresenter = new UserPresenter(this);

        findViewById(R.id.item_agent).setVisibility(ConfigManager.getInstance().isAgent() ? View.VISIBLE : View.GONE);
    }

    private void forceRefresh() {
        if (mSwipeRefreshLayout != null) {
            onUpdateUI();
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                    mPresenter.loadUserInfo(ConfigManager.getInstance().getId());
                    mPresenter.loadWallet();
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        forceRefreshIfNeed();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        forceRefreshIfNeed();
    }

    private boolean isUserVisible() {
        return getUserVisibleHint() && getActivity() != null && ((MainActivity) getActivity()).getCurrentTab() == 2;
    }

    private void forceRefreshIfNeed() {
        if (isUserVisible()) {
            forceRefresh();
        }
    }

    private void onUpdateUI() {
        ((TextView) findViewById(R.id.tv_name)).setText(ConfigManager.getInstance().getUserId());
        onUpdateBalance();
        ((TextView) findViewById(R.id.tv_version)).setText(com.buddies.lottery.utils.AppUtils.getAppVersionInfo());
        findViewById(R.id.tv_wallet_pwd_status).setVisibility(ConfigManager.getInstance().isWalletPwdExist() ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onUpdateBalance() {
        mSwipeRefreshLayout.setRefreshing(false);
        ((TextView) findViewById(R.id.tv_balance)).setText(LotteryUtils.formatBalance(ConfigManager.getInstance().getBalance()));
    }

    @Override
    public void onUpdateWallet() {
        onUpdateUI();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_reset_passward:
                ResetPasswordActivity.launch(getActivity());
                break;
            case R.id.item_wallet:
            case R.id.tv_charge:
                PayActivity.launch(getActivity());
                break;
            case R.id.tv_withdraw:
                WithdrawActivity.launch(getActivity());
                break;
            case R.id.item_bank:
                toBank();
                break;
            case R.id.item_wallet_pwd:
                UpdateWalletPwdActivity.launch(getActivity());
                break;
            case R.id.item_notification:
                CustomerActivity.launch(getActivity(), Constants.ONLINE_CUSTOMER_SERVICE);
                break;
            case R.id.item_lottery:
                LotteryBetRecordActivity.launch(getActivity());
                break;
            case R.id.item_agent:
                AgentRegisterActivity.launch(getActivity());
                break;
            case R.id.item_version:
                Beta.checkUpgrade();
                break;
            case R.id.item_log_report:
                CrashReport.postCatchedException(new Exception("日志上报"));
                ToastUtils.showShort("日志上报成功！");
                break;
            case R.id.item_logout:
                toLogout();
                break;
        }
    }

    private void toBank() {
        if (!ConfigManager.getInstance().isWalletPwdExist()) {
            new AlertDialog.Builder(getActivity())
                    .setMessage("请先设置资金密码？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            UpdateWalletPwdActivity.launch(getActivity());
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        } else {
            BankActivity.launch(getActivity());
        }
    }

    @Override
    public void onCheckWalletPwdSuccess(CheckWalletPwdResponse response) {
        hideProgressDialog();
        if (!response.result) {
            ToastUtils.showShort("您输入的资金密码有误！");
        } else {
            BankActivity.launch(getActivity());
        }
    }

    private void toLogout() {
        new AlertDialog.Builder(getActivity())
                .setMessage("确定退出当前账号吗？")
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ConfigManager.getInstance().logout();
                        getActivity().finish();
                        LoginActivity.launch(getActivity());
                    }
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    @Override
    public void onTabClick() {
        if (mScrollView != null && mScrollView.getScrollY() != 0) {
            mScrollView.scrollTo(0, 0);
        } else {
            forceRefresh();
        }
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
    }
}
